package xyz.zhzby.cyzx.judge.messenger;

import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xyz.zhzby.cyzx.judge.config.ApplicationDispatcher;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

/**
 * @author zby
 * @date 2022/02/04
 */
@Component
@Slf4j
@ApiModel("MQ消息接收类")
public class MessageReceiver implements MessageListener {

    @Autowired
    private ApplicationDispatcher dispatcher;

    @Override
    public void onMessage(Message message) {
        if (message instanceof MapMessage) {
            final MapMessage mapMessage = (MapMessage) message;

            try {
                String event = mapMessage.getString("event");

                if ("SubmissionCreated".equals(event)) {
                    newSubmissionHandler(mapMessage);
                } else {
                    log.warn(String.format("接收到未知消息. [消息为： %s]", event));
                }
            } catch (Exception ex) {
                log.error(ex.getMessage());
            }
        }
    }

    private void newSubmissionHandler(MapMessage mapMessage) throws JMSException {
        Long submissionId = mapMessage.getLong("submissionId");
        log.info(String.format("接收到新评测消息，ID： #%d", submissionId));

        dispatcher.onSubmissionCreated(submissionId);
    }

}
